package com.young.financial.utils;

import com.alibaba.fastjson.JSON;
import com.young.financial.config.UrlConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @auter miaozhenfei
 * @date 2019/7/30 18:31
 */

@Configuration
public class AccessTokenUtil {

    @Autowired
   private HttpClientUtils httpClientUtils;
    @Autowired
    private RedisUtils redisUtils;
    @Value("${balancePlatform.platfromMarking}")
    private   String platfromMarking;
    @Value("${balancePlatform.username}")
    private   String username;
    @Value("${balancePlatform.salt}")
    private   String salt;
    @Value("${balancePlatform.passWord}")
    private   String passWord;
    @Value("${balancePlatform.secretKey}")
    private   String secretKey;


    public  String getaccessToken() {
        String result  =null;
        String accessToken=null;
        String sign= JWT.md5Hex(platfromMarking + username +salt + passWord +secretKey);
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("platfromMarking",platfromMarking);
            map.put("username",username);
            map.put("salt",salt);
            map.put("passWord",passWord);
            map.put("secretKey",secretKey);
            map.put("sign",sign);

            result = httpClientUtils.doGet(UrlConstants.BALANCE_ACCESSTOKEN_URL, map);
            System.out.println("请求结果："+result);
            Map<String,Object> resultMap= (Map<String, Object>) JSON.parseObject(result,Map.class);
            String resultJson = resultMap.get("result").toString();
            Map<String, Object> toMap = JsonUtils.jsonToMap(resultJson);
            if(null != toMap && toMap.size()>1 && toMap.get("tgAccessToken") != null)  {
                accessToken = toMap.get("tgAccessToken").toString();
                int time = (int)toMap.get("time");
                redisUtils.setKey("blanceAccessToken", accessToken, time-1);
            }
            System.err.println(accessToken+"-------------accessToken0000000------");

        } catch (Exception e) {
            e.printStackTrace();
        }

        return accessToken;
    }
}
